<!--
 @description 帮助中心 - 类目列表
 @fileName tableData.vue
 @author zengqiongying
 @created 2022/01/10 11:41:46
-->
<template>
  <div class="custom-table-tree">
    <!-- :table-row-class-name="tableRowClassName" -->
    <table-box
      ref="refTable"
      :off-set="-10"
      :data="tableData"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :other-raw="otherRaws"
      table-default-expand-all
      table-row-key="id"
      :show-selection="false"
      :selected-arry.sync="tableSelected"
      :table-tree-props="{children: 'childrenCategorys', hasChildren: 'hasChildren'}"
      :show-custom-setting="false"
      @btnOperate="btnOperate"
    />
    <Edit v-if="showEdit" :visible.sync="showEdit" :parent-cate="parentCate" :detail-data="activeRow" @success="refreshTable" />
    <Move v-if="showMove" :visible.sync="showMove" :classify-name="classifyName" :detail-data="activeRow" @success="refreshTable" />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { fetchCategoryTree, deleteCategory, updateCategorySort } from '@/api/category'
import Edit from './components/Edit'
import Move from './components/Move'
export default {
  name: 'HelpCategoryTable',
  components: { Edit, Move },
  props: {
    classifyCode: {
      type: String,
      default: ''
    },
    classifyName: {
      type: String,
      default: ''
    },
    tabIndex:{
      type:Number,
      default:0
    },
    buttons: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const that = this
    return {
      tableData: [],
      tableSelected: [],
      otherRaws: {},
      otherFilters: [], // [{ id: 'applyType', property: 'applyType', value: this.classifyCode, operator: '=' }],
      tableConfig: {
        // interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/contentCategory/tree`,
        hideSearchBar: true,
        tabIndex: 0,
        apiHeader: {
          'Permission-PerCode': 'category',
          'Permission-App': 'content-center'
        },
        setting: [
          {
            prop: 'categoryName',
            label: '类目名称',
            minWidth: 300
          },
          {
            prop: 'iconUrl',
            label: '类目图标',
            minWidth: 100,
            overflowHidden: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              if (row.iconUrl) {
                const url = that.formatImageUrl(row.iconUrl)
                return (<div class='cate_img'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'state',
            label: '状态',
            width: 100,
            type: 'select',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'content-center',
              dictTypeCode: 'STATE'
            }
          },
          {
            prop: 'sort',
            label: '排序',
            minWidth: 200,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('top')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>)
              }
              if (this.hasPermission('up')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>)
              }
              if (this.hasPermission('down')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>)
              }
              if (this.hasPermission('bottom')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>)
              }
              return _h('div', btns)
              /* return (<div>
                <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 3)} class='btn-green my-txt-btn'>置顶</el-button>
                <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 1)} class='btn-green my-txt-btn'>上移</el-button>
                <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 2)} class='btn-green my-txt-btn'>下移</el-button>
                <el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 4)} class='btn-green my-txt-btn'>置底</el-button>
              </div>) */
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ createTime }) => {
              return parseTime(createTime)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          },
          {
            prop: 'operate',
            label: '操作',
            width: 180,
            fixed: 'right',
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              if (this.isProduction) {
                const btns = []
                if (this.hasPermission('edit')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleEdit.bind(this, row)} class='btn-green my-txt-btn'>编辑</el-button>)
                }
                if (this.hasPermission('del')) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleDelete.bind(this, row)} class='btn-green my-txt-btn'>删除</el-button>)
                }
                if (this.hasPermission('addChild') && row.state === 1) {
                  btns.push(<el-button type='text' size='mini' onClick={that.handleAddChild.bind(this, row)} class='btn-green my-txt-btn'>添加子类目</el-button>)
                }
                return _h('div', btns)
              } else {
                return (<div>
                  <el-button type='text' size='mini' onClick={that.handleEdit.bind(this, row)} class='btn-green my-txt-btn'>编辑</el-button>
                  <el-button type='text' size='mini' onClick={that.handleDelete.bind(this, row)} class='btn-green my-txt-btn'>删除</el-button>
                  <el-button type='text' size='mini' onClick={that.handleAddChild.bind(this, row)} class='btn-green my-txt-btn'>添加子类目</el-button>
                </div>)
              }
            }
          }
        ],
        btnList: !this.isProduction ? [{
          buttonName: '移动',
          optCode: 'move',
          outerFlag: true
        },
        {
          buttonName: '新增一级类目',
          optCode: 'add',
          outerFlag: true
        }] : null
      },
      sortTime: null, // 排序操作时间判断
      sorting: false, // 是否正在操作排序
      activeRow: '',
      parentCate: {
        classifyCode: this.classifyCode
      },
      showEdit: false,
      showMove: false
    }
  },
  computed: {
    moveTree() {
      const tree = [
        {
          id: '1',
          categoryName: this.classifyName,
          childrenCategorys: this.tableData
        }
      ]
      return tree
    }
  },
  created() {
    this.tableConfig.tabIndex=this.tabIndex
    if(this.tabIndex===0){
      this.getTree()
    }
  },
  methods: {
    hasPermission(code) {
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    getTree() {
      fetchCategoryTree(this.classifyCode).then(res => {
        this.tableData = res.data || []
      })
    },
    tableRowKey(row) {
      return row.id
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.tableSelected.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleEdit()
          break
        case 'move':
          if (!this.singleJudge(this.tableSelected, '移动', false)) {
            return
          }
          this.activeRow = this.tableSelected[0]
          this.$nextTick(() => {
            this.showMove = true
          })
          break
        default :
          break
      }
    },
    searchTableData() {
      this.$nextTick(() => {
        this.refreshTable(true)
      })
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.getTree()
      // this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
    },
    resetLayout() {
      this.$refs.refTable.resetLayout()
    },
    // 编辑/新增一级类目
    handleEdit(row) {
      if (row) {
        this.activeRow = row
        this.$set(this.parentCate, 'id', row.parentId || 0)
        this.$set(this.parentCate, 'name', row.parentName || '')
      } else {
        this.activeRow = ''
        this.$set(this.parentCate, 'id', '')
        this.$set(this.parentCate, 'name', '')
      }

      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 添加子类目
    handleAddChild(row) {
      // 判断是否为末级且有内容
      const hasContent = row.hasContent
      if (hasContent) {
        this.$message({
          message: '该类目为末级类目，不可新增子类目',
          type: 'warning'
        })
        return
      }
      this.activeRow = ''
      this.$set(this.parentCate, 'id', row.id || 0)
      this.$set(this.parentCate, 'name', row.categoryName || '')
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 删除
    handleDelete(row) {
      const hasChild = row.childrenCategorys && row.childrenCategorys.length // 该类目下含有子类目
      if (hasChild) {
        this.$message({
          type: 'warning',
          message: '该类目下含子类目，不可进行删除'
        })
        return
      }
      const hasContent = row.hasContent // 该类目下是否含有内容
      if (hasContent) {
        this.$message({
          type: 'warning',
          message: '该类目下含内容，不可进行删除'
        })
        return
      }
      this.$confirm('确认要删除当前所选类目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        deleteCategory(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        }).catch(() => {})
      })
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型： 1 上移 ， 2 下移 ，3置顶， 4 置底
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateCategorySort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    },
    refreshTableHeight() {
      this.$refs.refTable.refreshTableHeight()
    }
  }
}

</script>
<style lang='scss' scoped>
  .cate_img{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      width: 70px;
      height: 70px;
      object-fit: cover;
    }
  }
  .my-txt-btn{
    padding: 0 !important;
  }
  .custom-table-tree{
    /deep/ .el-table [class*=el-table__row--level] {
      .el-table__indent{
        float:left;
        display: inline-block;
        height: 16px;
      }
      .el-table__expand-icon{
        float:left;
        margin-top:6px;
      }
    }
    /deep/ .el-table__expand-icon~.table-other{
      display: inline-block;
      margin-top:6px;
    }
    /deep/ .el-table__indent~.table-other{
      display:inline-block;
    }
    /deep/.el-checkbox__input.is-disabled{
      visibility: hidden;
    }
  }
</style>
